import pool from '../config/database.js';

export const FacilityModel = {
  async getAllRecords() {
    try {
      const [rows] = await pool.query(`
        SELECT 
          id,
          facility,
          location,
          type,
          status,
          priority,
          DATE_FORMAT(report_date, '%Y-%m-%d') as reportDate,
          DATE_FORMAT(next_maintenance, '%Y-%m-%d') as nextMaintenance,
          created_at as createdAt,
          updated_at as updatedAt
        FROM maintenance_records 
        ORDER BY report_date DESC
      `);
      return rows;
    } catch (error) {
      console.error('Error in getAllRecords:', error);
      throw new Error('获取维护记录失败');
    }
  },

  async createRecord(record) {
    try {
      console.log('Creating maintenance record:', record);
      const [result] = await pool.query(
        `INSERT INTO maintenance_records (
          facility, 
          location, 
          type, 
          status, 
          priority, 
          report_date, 
          next_maintenance
        ) VALUES (?, ?, ?, ?, ?, ?, ?)`,
        [
          record.facility,
          record.location,
          record.type,
          record.status || '计划中',
          record.priority,
          record.reportDate,
          record.nextMaintenance
        ]
      );
      return result.insertId;
    } catch (error) {
      console.error('Error in createRecord:', error);
      throw new Error('创建维护记录失败');
    }
  },

  async updateRecord(id, record) {
    try {
      console.log('Updating maintenance record:', { id, record });
      
      // 检查记录是否存在
      const [existing] = await pool.query(
        'SELECT * FROM maintenance_records WHERE id = ?', 
        [id]
      );
      
      if (!existing || existing.length === 0) {
        throw new Error(`找不到ID为 ${id} 的维护记录`);
      }

      let result;
      // 如果只是更新状态
      if (Object.keys(record).length === 1 && record.status) {
        console.log('Updating status only:', record.status);
        [result] = await pool.query(
          `UPDATE maintenance_records 
          SET status = ?, updated_at = CURRENT_TIMESTAMP 
          WHERE id = ?`,
          [record.status, id]
        );
      } else {
        // 完整更新
        console.log('Full update:', record);
        [result] = await pool.query(
          `UPDATE maintenance_records 
          SET 
            facility = ?, 
            location = ?, 
            type = ?, 
            status = ?, 
            priority = ?, 
            report_date = ?, 
            next_maintenance = ?,
            updated_at = CURRENT_TIMESTAMP
          WHERE id = ?`,
          [
            record.facility,
            record.location,
            record.type,
            record.status,
            record.priority,
            record.reportDate,
            record.nextMaintenance,
            id
          ]
        );
      }

      if (result.affectedRows === 0) {
        throw new Error('更新失败，没有记录被修改');
      }

      return true;
    } catch (error) {
      console.error('Error in updateRecord:', error);
      throw new Error(`更新维护记录失败: ${error.message}`);
    }
  }
};